package com.whmnx.chitchat.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.classic.adapter.CommonRecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.component.UnreadCountTextView;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationLayout;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationListAdapter;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationListLayout;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationProvider;
import com.tencent.qcloud.tim.uikit.modules.conversation.base.ConversationInfo;
import com.tencent.qcloud.tim.uikit.modules.conversation.interfaces.IConversationAdapter;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.adapter.ChatListAdapter;
import com.whmnx.chitchat.adapter.ChatListAdapter2;
import com.whmnx.chitchat.base.BaseFragment;
import com.whmnx.chitchat.bean.AddGroupBean;
import com.whmnx.chitchat.bean.ChatMsgBean;
import com.whmnx.chitchat.bean.ChatMsgDatailBean;
import com.whmnx.chitchat.bean.DepartmentDean;
import com.whmnx.chitchat.bean.MessagePackBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.MainActivity;
import com.whmnx.chitchat.ui.chat.AddGroupActivity;
import com.whmnx.chitchat.ui.chat.AddMoreActivity;
import com.whmnx.chitchat.ui.chat.ChatActivity;
import com.whmnx.chitchat.ui.chat.ChatMiActivity;
import com.whmnx.chitchat.ui.my.MyActivity;
import com.whmnx.chitchat.utils.ImageUtil;
import com.whmnx.chitchat.utils.KeyboardUtils;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;
import com.whmnx.chitchat.view.Watermark;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.internal.Utils;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author : huang
 * date   : 2020/7/20 0020 18:15
 * version: 1.0
 *
 * @author Administrator
 */
public class MessageFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.ib_right)
    ImageButton ibRight;
    @BindView(R.id.ib_mi)
    ImageView ibMi;
    @BindView(R.id.iv_user)
    CircleImageView ivUser;
    @BindView(R.id.conversation_layout)
    ConversationLayout conversationLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refresh;

    @BindView(R.id.rv_chatMsg)
    RecyclerView rvChatMsg;
    private ChatListAdapter  mChatListAdapter;
    @BindView(R.id.message_search)
    EditText query;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    private int page = 1;
    private int Rows = 10;

    public static final String FOLLOW = "follow";


    @Override
    protected int getLayoutResource() {
        return R.layout.message_fragment;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        String com = SPUtil.getString(Constants.COM);
        String dep = SPUtil.getString(Constants.DEP);
        String nick = SPUtil.getString(Constants.NICKNAME);
        Watermark.getInstance().show(getActivity(), dep + com + nick);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.FAMILY)) {
                ImageUtil.setImage(ivUser, SPUtil.getString(Constants.HEAD_IMG));
            }else if (messageEvent.getMessageKey().equals(EventConstants.SENDMSG) || messageEvent.getMessageKey().equals(EventConstants.GROUP)
                    || messageEvent.getMessageKey().equals(EventConstants.NICKPOP)){
                getChatRecordList(true);
            }else if (messageEvent.getMessageKey().equals(EventConstants.ACCEPTMSG)){
                getChatRecordList(true);
                MessagePackBean msgJosn = (MessagePackBean)messageEvent.getMessageKey2();
                //密聊 1，
                int RecordType = msgJosn.getRecordType();
                if (RecordType == 1){
                    ibMi.setImageResource(R.mipmap.mi1);
                }
            }else if (messageEvent.getMessageKey().equals(EventConstants.ADDGROUP2)){  //加入群聊
                getChatRecordList(true);
            }
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i("onHiddenChanged","onHiddenChanged-----------");
      //  getChatRecordMIList();
      //  getChatRecordList(true);
       // getChatRecordMIList();
    }

    private void initView() {
        ImageUtil.setImage(ivUser, SPUtil.getString(Constants.HEAD_IMG));
        ibRight.setOnClickListener(this);
        // 初始化会话列表
        conversationLayout.initDefault();
        ivUser.setOnClickListener(this);
        ibMi.setOnClickListener(this);

        // 获取 TitleBarLayout
        TitleBarLayout titleBarLayout = conversationLayout.findViewById(R.id.conversation_title);
        titleBarLayout.setVisibility(View.GONE);
        ConversationListLayout listLayout = conversationLayout.getConversationList();
        listLayout.enableItemRoundIcon(true);// 设置 item 头像是否显示圆角，默认是方形
        listLayout.disableItemUnreadDot(true);// 设置 item 是否不显示未读红点，默认显示

        conversationLayout.getConversationList().setOnItemClickListener((view, position, conversationInfo) -> {
            //此处为demo的实现逻辑，更根据会话类型跳转到相关界面，开发者可根据自己的应用场景灵活实现
          //  startChatActivity(conversationInfo);
        });

        rvChatMsg.setLayoutManager(new LinearLayoutManager(getActivity()));
      //  rvChatMsg.setItemAnimator(new DefaultItemAnimator());
        rvChatMsg.setItemAnimator(null);
        mChatListAdapter = new ChatListAdapter(getActivity());
      //  RecyclerView.RecycledViewPool pool= new RecyclerView.RecycledViewPool();
       // pool.setMaxRecycledViews(0, 10);
      //  rvChatMsg.setRecycledViewPool(pool);
       /* rvChatMsg.getItemAnimator().setAddDuration(0);
        rvChatMsg.getItemAnimator().setChangeDuration(0);
        rvChatMsg.getItemAnimator().setMoveDuration(0);
        rvChatMsg.getItemAnimator().setRemoveDuration(0);
        rvChatMsg.getItemAnimator().setChangeDuration(0);*/
//        ((SimpleItemAnimator)rvChatMsg.getItemAnimator()).setSupportsChangeAnimations(false);
        rvChatMsg.setAdapter(mChatListAdapter);

        refresh.setOnRefreshListener(refreshLayout -> getChatRecordList(true));
        refresh.setOnLoadMoreListener(refreshLayout -> getChatRecordList(false));
        getChatRecordList(true);
       // getChatRecordMIList();


        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                search(s.toString().trim());
            }

            @Override
            public void afterTextChanged(Editable s) {
                KeyboardUtils.showKeyBoard(getActivity(),getActivity().getCurrentFocus());
                tvCancel.setVisibility(View.VISIBLE);
            }
        });


        /*query.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击搜索的时候隐藏软键盘
                // hideKeyboard(EditText);
                // 在这里写搜索的操作,一般都是网络请求数据
                if (!TextUtils.isEmpty(v.getText().toString().trim())) {
                    search(v.getText().toString().trim());
                }else {
                    UItils.showToastSafe("请输入内容");
                }
                return true;
            }
            return false;
        });*/


        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.setText("");
                search("");
                tvCancel.setVisibility(View.GONE);
                KeyboardUtils.hideKeyBoard(getActivity(), getActivity().getCurrentFocus());
            }
        });
    }

    private void getChatRecordMIList() {
        Map<String, Object> params = new HashMap<>();
        params.put("UserID",SPUtil.getString(Constants.USERID));
        params.put("Page",page + "");
        params.put("Rows",Rows + "");
        params.put("RecordType","1");
        HttpClient.get(getActivity(), Constants.GETCHATRECORDLIST, params,new CallBack<ChatMsgDatailBean>() {
            @Override
            public void onSuccess(ChatMsgDatailBean result) {
                if (result.List.size() > 0){
                    ibMi.setImageResource(R.mipmap.mi1);
                }else {
                    ibMi.setImageResource(R.mipmap.mimi2);
                }
            }
        });
    }

    private void search(String trim) {
        Map<String, Object> params = new HashMap<>();
        params.put("UserID", SPUtil.getString(Constants.USERID));
        params.put("Page", "1");
        params.put("Rows", "50");
        params.put("Con", trim);

        HttpClient.get(getActivity(), Constants.GETCHATRECORDLIST, params, new CallBack<ChatMsgDatailBean>() {
            @Override
            public void onSuccess(ChatMsgDatailBean result) {
                // mDataSource.clear();
                //mDataSource.addAll(result.List);
                if (result.List.size() > 0){
                    SPUtil.put(Constants.TRIM,trim);
                    mChatListAdapter.replaceAll(result.List, true);
                    if (TextUtils.isEmpty(trim)){
                        tvCancel.setVisibility(View.GONE);
                    }else {
                        tvCancel.setVisibility(View.VISIBLE);
                    }

                }else {
                    SPUtil.put(Constants.TRIM,"");
                  // UItils.showToastSafe("暂无聊天记录");
                    mChatListAdapter.addAll(result.List);
                   // tvCancel.setVisibility(View.GONE);
                }
            }
        });
    }

    private void getChatRecordList(boolean isRefresh) {
        if (isRefresh) page = 1;
        Map<String, Object> params = new HashMap<>();
        params.put("UserID",SPUtil.getString(Constants.USERID));
        params.put("Page",page + "");
        params.put("Rows",Rows + "");
        params.put("RecordType","0");
        HttpClient.get(getActivity(), Constants.GETCHATRECORDLIST, params,new CallBack<ChatMsgDatailBean>() {
            @Override
            public void onSuccess(ChatMsgDatailBean result) {
               // getChatRecordMIList();
                if (isRefresh){
                    refresh.finishRefresh(true);
                    mChatListAdapter.replaceAll(result.List);
                }else {
                    if (result.List.size() > 0) {
                        refresh.finishLoadMore(true);
                        mChatListAdapter.addAll(result.List);
                    }else {
                        refresh.finishLoadMoreWithNoMoreData();
                    }
                }
                page++;
                SPUtil.put(Constants.ALLFORUMMESSAGE,result.AllForumMessage);
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.MSGNUM);
                messageEvent.setMessageValue(result.AllUnreadNum + "");
                    EventBus.getDefault().post(messageEvent);
            }
        });
    }

    private void startChatActivity(ChatMsgBean chatMsgBean) {
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setType(chatMsgBean.getType() == 1 ? TIMConversationType.Group : TIMConversationType.C2C);
        chatInfo.setId(chatMsgBean.getObjectID());
        chatInfo.setChatName(chatMsgBean.getName());
        Intent intent = new Intent(getActivity(), ChatActivity.class);
        intent.putExtra(Constants.CHAT_INFO, chatInfo);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getActivity().startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_user){
            UItils.startActivity(MyActivity.class);
        }else if (v.getId() == R.id.ib_mi){
            UItils.startActivity(ChatMiActivity.class);
           // startActivity(new Intent(getActivity(), MainActivity.class).putExtra(FOLLOW, true));
        }else {
            showAddPopWindow();
        }
    }

    private void showAddPopWindow() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_message_contact, null);
        int popWindowWidth = (int) (UItils.getDeviceDensity().widthPixels / 3);
        PopupWindow mPopWindow = new PopupWindow(view,popWindowWidth, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(view);
        // 设置PopupWindow的背景
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setTouchable(true);
        // 这个很重要
        mPopWindow.getContentView().setFocusable(true);
        mPopWindow.getContentView().setFocusableInTouchMode(true);

        LinearLayout ll_phone = view.findViewById(R.id.ll_phone);
        LinearLayout ll_weixin = view.findViewById(R.id.ll_weixin);

        mPopWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mPopWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        mPopWindow.showAsDropDown(ibRight, 0, 0);


        ll_phone.setOnClickListener(v -> {
            //搜索添加好友
            Intent intent = new Intent(UItils.getContext(), AddMoreActivity.class);
            //  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(TUIKitConstants.GroupType.GROUP, false);
            getActivity().startActivity(intent);
            mPopWindow.dismiss();
        });

        ll_weixin.setOnClickListener(v -> {
            Intent intent = new Intent(UItils.getContext(), AddGroupActivity.class);
            // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("type", 10);
            getActivity().startActivity(intent);
           // UItils.startActivity(AddGroupActivity.class);
            mPopWindow.dismiss();
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
